package com.supermarket.manage.business.product.controller;

import com.supermarket.manage.common.constant.ProductConstant;
import com.supermarket.manage.common.dto.CodeStatus;
import com.supermarket.manage.common.dto.ResponseResult;
import com.supermarket.manage.common.dto.prod.response.CategoryDto;
import com.supermarket.manage.common.pojo.ProductCategory;
import com.supermarket.manage.common.validation.CheckGroup;
import com.supermarket.manage.provider.api.product.ProductCategoryService;
import com.supermarket.manage.provider.api.product.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.Set;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-03-08 19:25
 **/
@RestController
@RequestMapping("/category")
@Api(value = "ProductCategoryController", tags = "商品分类管理接口")
public class ProductCategoryController {

    @Reference(version = "1.0.0")
    private ProductCategoryService productCategoryService;

    @Reference(version = "1.0.0")
    private ProductService productService;

    @PreAuthorize("hasAuthority('/logined')")
    @GetMapping("/getCategoryList/{buyerId}")
    @ApiOperation(value = "获取商品分类列表", notes = "获取商品分类列表(参数：客户id)")
    public ResponseResult<Set<CategoryDto>> getCategoryList(@PathVariable String buyerId) {
        Set<CategoryDto> categories = productCategoryService.getCategoryList(buyerId);
        return new ResponseResult<>(CodeStatus.OK, "查询成功", categories);
    }

    @PreAuthorize("hasAnyAuthority('/','/product/manage')")
    @PostMapping("/add")
    @ApiOperation(value = "添加商品分类", notes = "添加商品分类(添加顶级分类时 pid 为 0 )")
    public ResponseResult<Void> addCategory(@Validated({CheckGroup.Add.class})
                                            @RequestBody ProductCategory category) {
        Integer count = productCategoryService.getCountByCname(category.getCname(), category.getBuyerId());
        if (count > 0) {
            return new ResponseResult<>(CodeStatus.FAIL, "分类名称重复");
        }
        //不是一级分类，则检查父分类id是否合法
        if (!category.getFid().equals(ProductConstant.TOP_CAT_PID)) {
            ProductCategory father = productCategoryService.getCategoryByCid(category.getFid());
            if (father == null) {
                return new ResponseResult<>(CodeStatus.FAIL, "父分类不存在");
            }
            //判断是否是二级分类
            if (!father.getFid().equals(ProductConstant.TOP_CAT_PID)) {
                ProductCategory grandFather = productCategoryService.getCategoryByCid(father.getFid());
                if (grandFather == null) {
                    return new ResponseResult<>(CodeStatus.FAIL, "祖父分类不存在");
                }
                //判断是否是三级分类
                if (!grandFather.getFid().equals(ProductConstant.TOP_CAT_PID)) {
                    return new ResponseResult<>(CodeStatus.FAIL, "最多添加三级分类");
                }
            }
        }
        Boolean aBoolean = productCategoryService.addCategory(category);
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "添加成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "添加失败");
    }

    @PreAuthorize("hasAuthority('/logined')")
    @GetMapping("/getByCid/{cid}")
    @ApiOperation(value = "根据id获取分类信息", notes = "根据id获取分类信息")
    public ResponseResult<ProductCategory> getByCid(@NotBlank(message = "分类id不能为空")
                                                    @PathVariable String cid) {
        ProductCategory category = productCategoryService.getCategoryByCid(cid);
        if (category == null) {
            return new ResponseResult<>(CodeStatus.FAIL, "该分类不存在");
        }
        return new ResponseResult<>(CodeStatus.OK, "查询成功", category);
    }

    @PreAuthorize("hasAnyAuthority('/','/product/manage')")
    @GetMapping("/deleteByCid/{cid}")
    @ApiOperation(value = "删除商品分类", notes = "删除商品分类")
    public ResponseResult<Void> deleteByCid(@NotBlank(message = "分类id不能为空")
                                            @PathVariable String cid) {
        ProductCategory category = productCategoryService.getCategoryByCid(cid);
        if (category == null) {
            return new ResponseResult<>(CodeStatus.FAIL, "删除失败，该分类不存在");
        }
        Integer prodCount = productService.getProdCountByCid(cid);
        if (prodCount > 0) {
            return new ResponseResult<>(CodeStatus.FAIL, "删除失败，该分类已被商品使用");
        }
        Integer count = productCategoryService.getChildCountByCid(cid);
        if (count > 0) {
            return new ResponseResult<>(CodeStatus.FAIL, "删除失败，该分类下还有子分类");
        }
        Boolean aBoolean = productCategoryService.deleteByCid(cid, category.getBuyerId());
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "删除成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "删除失败");
    }

    @PreAuthorize("hasAnyAuthority('/','/product/manage')")
    @PostMapping("/updateCnameByCid")
    @ApiOperation(value = "修改分类名称", notes = "修改分类名称（参数：主键id，分类名称，客户id）")
    public ResponseResult<Void> updateCnameByCid(@Validated({CheckGroup.Update.class})
                                                 @RequestBody ProductCategory category) {
        ProductCategory productCategory = productCategoryService.getCategoryByCid(category.getCid());
        if (productCategory == null) {
            return new ResponseResult<>(CodeStatus.FAIL, "更新失败，分类不存在");
        }
        if (productCategory.getCname().equals(category.getCname())) {
            return new ResponseResult<>(CodeStatus.FAIL, "商品名称与未修改前一致，请重新输入");
        }
        Integer count = productCategoryService.getCountByCname(category.getCname(), category.getBuyerId());
        if (count > 0) {
            return new ResponseResult<>(CodeStatus.OK, "分类名称重复");
        }
        Boolean aBoolean = productCategoryService.updateCnameByCid(category);
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "修改成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "修改失败");
    }
}
